package com.itHaipeng.dao.impl;

import com.itHaipeng.dao.IDaoAccount;
import com.itHaipeng.pojo.Account;
import com.itHaipeng.service.utils.ConnectionUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

@Repository(value = "iDaoAccountImpl")
public class IDaoAccountImpl implements IDaoAccount {
    @Autowired
    private QueryRunner queryRunner;
    @Autowired
    private ConnectionUtil connectionUtil;
    @Override
    public Account findByName(String name) {
        try {
            List<Account> accountList = queryRunner.query(connectionUtil.getThreadConnection(),"select *from account where name=?", new BeanListHandler<>(Account.class), name);
            if (accountList.size() != 1){
                throw new RuntimeException("数据输入的有问题");
            }
            return accountList.get(0);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Account> queryAll() {
        try {
            return queryRunner.query(connectionUtil.getThreadConnection(),"select * from account;",new BeanListHandler<>(Account.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void upData(Account account) {
        try {
            queryRunner.update(connectionUtil.getThreadConnection(), "update account set money=?,name=?where id=?",account.getMoney(),account.getName(),account.getId());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
